const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456', // 替换为您的数据库密码
  port: 3306
};

async function initDatabase() {
  let connection;
  
  try {
    console.log('🔌 连接到MySQL服务器...');
    connection = await mysql.createConnection(dbConfig);
    console.log('✅ MySQL连接成功');
    
    // 读取SQL脚本
    const sqlPath = path.join(__dirname, '../database/chatime.sql');
    const sqlContent = fs.readFileSync(sqlPath, 'utf8');
    
    console.log('📖 读取SQL脚本文件...');
    
    // 分割SQL语句
    const statements = sqlContent
      .split(';')
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.length > 0 && !stmt.startsWith('--'));
    
    console.log(`📝 找到 ${statements.length} 条SQL语句`);
    
    // 逐条执行SQL语句
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i];
      if (statement.trim()) {
        try {
          console.log(`🔄 执行第 ${i + 1} 条语句...`);
          await connection.execute(statement);
          console.log(`✅ 第 ${i + 1} 条语句执行成功`);
        } catch (error) {
          console.error(`❌ 第 ${i + 1} 条语句执行失败:`, error.message);
          // 如果是表已存在的错误，继续执行
          if (error.code === 'ER_TABLE_EXISTS_ERROR' || error.code === 'ER_DUP_ENTRY') {
            console.log(`⚠️  表已存在或数据已存在，跳过...`);
            continue;
          }
          throw error;
        }
      }
    }
    
    console.log('🎉 数据库初始化完成！');
    
    // 验证数据
    console.log('🔍 验证数据...');
    
    const [users] = await connection.execute('SELECT COUNT(*) as count FROM users');
    console.log(`👥 用户数量: ${users[0].count}`);
    
    const [friends] = await connection.execute('SELECT COUNT(*) as count FROM friends');
    console.log(`👫 好友关系数量: ${friends[0].count}`);
    
    const [dynamics] = await connection.execute('SELECT COUNT(*) as count FROM dynamics');
    console.log(`📝 动态数量: ${dynamics[0].count}`);
    
    const [comments] = await connection.execute('SELECT COUNT(*) as count FROM dynamic_comments');
    console.log(`💬 评论数量: ${comments[0].count}`);
    
    const [likes] = await connection.execute('SELECT COUNT(*) as count FROM dynamic_likes');
    console.log(`👍 点赞数量: ${likes[0].count}`);
    
    const [messages] = await connection.execute('SELECT COUNT(*) as count FROM chat_messages');
    console.log(`💭 聊天消息数量: ${messages[0].count}`);
    
    const [sessions] = await connection.execute('SELECT COUNT(*) as count FROM chat_sessions');
    console.log(`💬 聊天会话数量: ${sessions[0].count}`);
    
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error);
    throw error;
  } finally {
    if (connection) {
      await connection.end();
      console.log('🔌 数据库连接已关闭');
    }
  }
}

// 运行初始化
if (require.main === module) {
  initDatabase()
    .then(() => {
      console.log('🎊 数据库初始化脚本执行完成！');
      process.exit(0);
    })
    .catch((error) => {
      console.error('💥 数据库初始化脚本执行失败:', error);
      process.exit(1);
    });
}

module.exports = { initDatabase }; 